package com.blobfish.customer;

import cn.hutool.core.lang.Console;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.blobfish.kit.BlockThreadPool;
import com.blobfish.kit.QuerierUtil;
import com.blobfish.kit.TranslatedCacheUtil;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 翻译者
 *
 * @author huangbo
 */
public class Translator {
    private static final String FILE_PATH_RESULT = "E:\\workspace\\translateJson\\src\\main\\resources\\data\\result.json";

    public static void main(String[] args) {
        BlockThreadPool pool = new BlockThreadPool(30);
        final Map<String, String> resultMap = TranslatedCacheUtil.getResultMap();
        final AtomicInteger taskNum = new AtomicInteger(resultMap.size());
        final AtomicInteger index = new AtomicInteger(0);
        Console.log("准备翻译，共需翻译{}项-----------------------", taskNum.get());
        Iterator it = resultMap.entrySet().iterator();
        while (it.hasNext()) {
            final Map.Entry<String, String> entry = (Map.Entry) it.next();
            String key = entry.getKey();
            String value = entry.getValue();
            if (StrUtil.isBlank(value)) {
                pool.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Console.log("准备翻译：{}", entry.getKey());
                            String result = QuerierUtil.getInstance().querier(entry.getKey(), index.getAndAdd(1));
                            TranslatedCacheUtil.putResult(entry.getKey(), result);
                            Console.log("{}翻译完毕，结果:{},剩余{}项", entry.getKey(), result, taskNum.decrementAndGet());
                            ThreadUtil.safeSleep(1000);
                        } catch (Exception e) {
                            Console.error(e.getMessage());
                        }
                    }
                });
            }
        }
        pool.destory();
    }
}
